import Tools from "../../framework/utils/Tools"; 
 

/**
 * 数据更新类型
 */
 export enum DATA_UP_TYPE {
    ADD =  1,//添加
    DEL =  2,//删除
    UPDATE = 3 //更新
}

/**
 * 基础玩家数据
 */
 
export default class PlayerBase {
    //用于记录更新前的某些值
    private beferDict = {};
    private data:any = null;
    protected init(data){
        this.data = data; 
    } 

    protected getData(){
        return this.data;
    }
 
     /**
     * 共用的同步  没有特殊的结构就用这一套
     */
    protected defaultSynchronInfo(name:string,info:object){  
        var base = Tools.getValid(this.data[name], {});
        if(typeof base == "object" && typeof info == "object"){
            for (var k in info) { 
                base[k] = info[k];
            }
            this.data[name] = base;
        }else{
            this.data[name] = info;
        }  
    }
 
    /**
     * 更新增删改查    先删  后加  再更新
     */
    protected updateCrud(keyName:string,data:Object){
        var base = this.data[keyName];
        if ( Tools.isEmpty( base ) ) {
            this.data[ keyName ] = {};
            base = this.data[ keyName ];
        }

        for ( var k in data ) {
            if ( data[k] && Tools.isValid( data[k].upTyp ) && data[k].upTyp > 0 ) {
                // 特殊增、删、改处理
                var datas = data[k].datas;
                if ( Tools.isEmpty( datas ) ) continue;
                this.syncSpecialData( base[k], datas );
            } else {
                base[k] = data[k];
            }
        } 
    } 
 
   // 同步增、删、改
    syncSpecialData( base, datas ) {
        for ( var k in datas ) {
            var data = datas[k];
            switch (data.typ) {
                case DATA_UP_TYPE.ADD:
                case DATA_UP_TYPE.UPDATE:
                    // 增加、修改
                    if ( Tools.isEmpty(data.index) ) continue;
                    base[data.index] = data.data;
                    break;
                case DATA_UP_TYPE.DEL:
                    // 删除
                    if ( Tools.isEmpty(data.index) ) continue;  
                    if(Array.isArray(base)){
                        base.splice(data.index,1); 
                    }else{
                        delete base[ data.index ];
                    }

                    break;
                default:
                    break;
            }
        }
    }

}
